package com.glodon.paas.databag.dao.impl;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.glodon.paas.databag.dao.DatabagTaskRepositoryCustom;
import com.glodon.paas.databag.model.DatabagTask;
import com.glodon.paas.job.model.TaskStatus;

public class DatabagTaskRepositoryJpaImpl implements DatabagTaskRepositoryCustom {
    
    @PersistenceContext
    private EntityManager entityManager;
    
    private final String hql_update = "UPDATE DatabagTask task SET task.responseTime = :responseTime, task.progress = :progress, "+
            "task.status = :status, task.message = :message ";

    @Override
    public boolean modifyPkgTaskProgress(String taskId, DatabagTask task) {
        String jpql = null;
        TaskStatus status = task.getStatus();
        if (status == null) {
            return false;
        }
        if (TaskStatus.success.equals(status) || TaskStatus.failure.equals(status) || TaskStatus.canceled.equals(status)) {
            jpql = hql_update + "WHERE task.taskId = :taskId";
        } else {
            jpql = hql_update + "WHERE task.progress < :progress and task.taskId = :taskId";
        }
        Query query = entityManager.createQuery(jpql);
        query.setParameter("responseTime", new Date());
        query.setParameter("progress", task.getProgress());
        query.setParameter("status", status);
        query.setParameter("message", task.getMessage());
        //query.setParameter("output", task.getOutput());
        if (TaskStatus.success.equals(status) || TaskStatus.failure.equals(status) || TaskStatus.canceled.equals(status)) {
            query.setParameter("taskId", task.getTaskId());
        } else {
            query.setParameter("progress", task.getProgress());
            query.setParameter("taskId", task.getTaskId());
        }
        int update = query.executeUpdate();
        return update > 0;
    }

}
